/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.dev/license
 */

import {
  Directive,
  ElementRef,
  Injector,
  NgModule,
  input,
  output,
} from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { UpgradeComponent, UpgradeModule } from "@angular/upgrade/static";
import { Ng2HeroesComponent } from "./components/ng2-heroes.component";
import { type Hero } from "./interface/hero";
import { ng1AppModule } from "./ng1.module";
import { HeroesService } from "./services/hero";
import { TextFormatter } from "./utils/textFormatter";

// This Angular directive will act as an interface to the "upgraded" AngularJS component
@Directive({
  selector: "ng1-hero",
  standalone: false,
})
export class Ng1HeroComponentWrapper extends UpgradeComponent {
  // The names of the input and output properties here must match the names of the
  // `<` and `&` bindings in the AngularJS component that is being wrapped
  hero = input.required<Hero>();

  onRemove = output<void>();

  constructor(elementRef: ElementRef, injector: Injector) {
    // We must pass the name of the directive as used by AngularJS to the super
    super("ng1Hero", elementRef, injector);
  }
}

// This NgModule represents the Angular pieces of the application
@NgModule({
  declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper],
  providers: [
    // Register an Angular provider whose value is the "upgraded" AngularJS service
    {
      provide: TextFormatter,
      useFactory: (i: { get: (name: string) => TextFormatter }) =>
        i.get("textFormatter"),
      deps: ["$injector"],
    },
    HeroesService,
  ],
  // We must import `UpgradeModule` to get access to the AngularJS core services
  imports: [BrowserModule, UpgradeModule],
})
export class Ng2AppModule {
  constructor(private upgrade: UpgradeModule) {}

  ngDoBootstrap() {
    // We bootstrap the AngularJS app.
    this.upgrade.bootstrap(document.body, [ng1AppModule.name]);
  }
}
